<?php
/**
 * 活动申请API - 适配现有数据库版本
 * 使用现有的数据库表：activity_applications, users 等
 */

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    exit;
}

// 数据库配置
$dbConfig = [
    'host' => 'localhost',
    'name' => 'nzy_congqian_cn', 
    'user' => 'nzy_congqian_cn',
    'pass' => 'FsnXrDfDhm4wFJSX',
    'charset' => 'utf8mb4'
];

// 数据库连接
try {
    $dsn = "mysql:host={$dbConfig['host']};dbname={$dbConfig['name']};charset={$dbConfig['charset']}";
    $pdo = new PDO($dsn, $dbConfig['user'], $dbConfig['pass']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    jsonResponse([
        'success' => false,
        'message' => '数据库连接失败: ' . $e->getMessage()
    ]);
}

// 响应函数
function jsonResponse($data) {
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

function success($data = null, $message = '操作成功') {
    jsonResponse([
        'code' => 200,
        'success' => true,
        'message' => $message,
        'data' => $data,
        'timestamp' => time()
    ]);
}

function error($message = '操作失败', $code = 400) {
    jsonResponse([
        'code' => $code,
        'success' => false,
        'message' => $message,
        'data' => null,
        'timestamp' => time()
    ]);
}

// 保存常用观众信息
function saveCommonVisitorInfo($userId, $name, $phone, $idNumber = null, $idType = '身份证') {
    global $pdo;
    
    try {
        // 检查是否已存在相同的观众信息（通过姓名和手机号）
        $checkSql = "SELECT id FROM common_visitors 
                     WHERE user_id = ? AND name = ? AND phone = ?";
        $checkStmt = $pdo->prepare($checkSql);
        $checkStmt->execute([$userId, $name, $phone]);
        
        if (!$checkStmt->fetch()) {
            // 不存在则新增
            $insertSql = "INSERT INTO common_visitors 
                         (user_id, name, id_type, id_number, phone, created_at, updated_at)
                         VALUES (?, ?, ?, ?, ?, NOW(), NOW())";
            $insertStmt = $pdo->prepare($insertSql);
            $insertStmt->execute([$userId, $name, $idType, $idNumber, $phone]);
        } else {
            // 存在则更新最后修改时间
            $updateSql = "UPDATE common_visitors 
                         SET updated_at = NOW() 
                         WHERE user_id = ? AND name = ? AND phone = ?";
            $updateStmt = $pdo->prepare($updateSql);
            $updateStmt->execute([$userId, $name, $phone]);
        }
    } catch (Exception $e) {
        // 常用观众信息保存失败不影响主要功能
        error_log("Save common visitor failed: " . $e->getMessage());
    }
}

// 验证token（兼容版本）
function verifyToken($token) {
    global $pdo;
    
    if (empty($token)) {
        return false;
    }
    
    // 移除Bearer前缀
    if (strpos($token, 'Bearer ') === 0) {
        $token = substr($token, 7);
    }
    
    try {
        // 先检查表结构
        $hasTokenField = false;
        try {
            $columns = $pdo->query("SHOW COLUMNS FROM users LIKE 'token'")->fetchAll();
            $hasTokenField = (count($columns) > 0);
        } catch (Exception $e) {
            $hasTokenField = false;
        }
        
        if ($hasTokenField) {
            // 尝试新的token验证
            $sql = "SELECT * FROM users WHERE token = ?";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$token]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($user) {
                // 检查用户状态和过期时间
                $isActive = ($user['status'] == 'active' || $user['status'] == 1);
                $isNotExpired = empty($user['token_expires']) || strtotime($user['token_expires']) > time();
                
                if ($isActive && $isNotExpired) {
                    return $user;
                }
                
                // 如果用户存在但token过期，更新过期时间并返回用户（兼容处理）
                if ($isActive) {
                    try {
                        $updateSql = "UPDATE users SET token_expires = DATE_ADD(NOW(), INTERVAL 7 DAY) WHERE id = ?";
                        $updateStmt = $pdo->prepare($updateSql);
                        $updateStmt->execute([$user['id']]);
                        return $user;
                    } catch (Exception $e) {
                        // 更新失败，继续下面的验证
                    }
                }
            }
        }
        
        // 备用方案1：尝试将token作为openid来验证
        $sql = "SELECT * FROM users WHERE openid = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$token]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($user) {
            $isActive = ($user['status'] == 'active' || $user['status'] == 1);
            if ($isActive) {
                return $user;
            }
        }
        
        // 备用方案2：尝试更宽松的状态检查
        $sql = "SELECT * FROM users WHERE (openid = ? OR (token IS NOT NULL AND token = ?)) AND status != 0";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$token, $token]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($user) {
            return $user;
        }
        
        return false;
        
    } catch (Exception $e) {
        // 最基础的验证
        try {
            $sql = "SELECT * FROM users WHERE openid = ? LIMIT 1";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$token]);
            return $stmt->fetch(PDO::FETCH_ASSOC);
        } catch (Exception $e2) {
            return false;
        }
    }
}

// 获取认证token
function getAuthToken() {
    $headers = getallheaders();
    $authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
    
    if (strpos($authHeader, 'Bearer ') === 0) {
        return substr($authHeader, 7);
    }
    
    return $_GET['token'] ?? $_POST['token'] ?? '';
}

// 获取当前用户
function getCurrentUser() {
    $token = getAuthToken();
    if (!$token) {
        error('需要登录', 401);
    }
    
    $user = verifyToken($token);
    if (!$user) {
        error('登录已过期，请重新登录', 401);
    }
    
    return $user;
}

// 创建活动申请
function createActivityApplication() {
    global $pdo;
    
    $user = getCurrentUser();
    $input = json_decode(file_get_contents('php://input'), true);
    
    // 验证必填字段
    $required = [
        'activity_name', 'activity_type', 'activity_date', 'start_time', 'end_time',
        'participant_count', 'organizer', 'contact_name', 'contact_phone', 'activity_description'
    ];
    
    foreach ($required as $field) {
        if (empty($input[$field])) {
            error("缺少必填字段: $field");
        }
    }
    
    $activityName = $input['activity_name'];
    $activityType = $input['activity_type'];
    $activityDate = $input['activity_date'];
    $startTime = $input['start_time'];
    $endTime = $input['end_time'];
    $participantCount = intval($input['participant_count']);
    $organizer = $input['organizer'];
    $contactName = $input['contact_name'];
    $contactPhone = $input['contact_phone'];
    $activityDescription = $input['activity_description'];
    $venueRequirements = $input['venue_requirements'] ?? '';
    $equipmentNeeds = $input['equipment_needs'] ?? '';
    
    // 验证参数
    if ($participantCount < 1 || $participantCount > 500) {
        error('参与人数必须在1-500人之间');
    }
    
    if (!preg_match('/^1[3-9]\d{9}$/', $contactPhone)) {
        error('手机号格式不正确');
    }
    
    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $activityDate)) {
        error('日期格式错误');
    }
    
    if (!preg_match('/^\d{2}:\d{2}$/', $startTime) || !preg_match('/^\d{2}:\d{2}$/', $endTime)) {
        error('时间格式错误，请使用 HH:MM 格式');
    }
    
    // 检查开始时间和结束时间
    if (strtotime($startTime) >= strtotime($endTime)) {
        error('结束时间必须晚于开始时间');
    }
    
    // 检查日期是否为未来日期
    $today = date('Y-m-d');
    if ($activityDate < $today) {
        error('不能申请过去的日期');
    }
    
    // 检查是否超过90天
    $maxDate = date('Y-m-d', strtotime('+90 days'));
    if ($activityDate > $maxDate) {
        error('只能申请90天内的日期');
    }
    
    try {
        $pdo->beginTransaction();
        
        // 检查是否为闭馆日
        $closureSql = "SELECT * FROM museum_closure_dates 
                       WHERE closure_date = ? AND is_active = 1";
        $closureStmt = $pdo->prepare($closureSql);
        $closureStmt->execute([$activityDate]);
        $closure = $closureStmt->fetch(PDO::FETCH_ASSOC);
        
        if ($closure) {
            throw new Exception("该日期为闭馆日：{$closure['reason']}");
        }
        
        // 检查活动名称长度
        if (mb_strlen($activityName) > 100) {
            throw new Exception('活动名称不能超过100个字符');
        }
        
        // 检查该用户是否已有相同日期的活动申请
        $existingSql = "SELECT id FROM activity_applications 
                       WHERE user_id = ? AND activity_date = ? AND status IN (0, 1)";
        $existingStmt = $pdo->prepare($existingSql);
        $existingStmt->execute([$user['id'], $activityDate]);
        
        if ($existingStmt->fetch()) {
            throw new Exception('您在该日期已有活动申请，请选择其他日期');
        }
        
        // 创建活动申请记录
        $insertSql = "INSERT INTO activity_applications 
                     (user_id, activity_name, activity_type, activity_date, start_time, end_time,
                      participant_count, organizer, contact_name, contact_phone, activity_description,
                      venue_requirements, equipment_needs, status, created_at, updated_at)
                     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, NOW(), NOW())";
        
        $insertStmt = $pdo->prepare($insertSql);
        $insertStmt->execute([
            $user['id'],
            $activityName,
            $activityType,
            $activityDate,
            $startTime,
            $endTime,
            $participantCount,
            $organizer,
            $contactName,
            $contactPhone,
            $activityDescription,
            $venueRequirements,
            $equipmentNeeds
        ]);
        
        $applicationId = $pdo->lastInsertId();
        
        // 自动生成常用观众信息记录
        saveCommonVisitorInfo($user['id'], $contactName, $contactPhone);
        
        $pdo->commit();
        
        success([
            'application_id' => $applicationId,
            'activity_name' => $activityName,
            'activity_type' => $activityType,
            'activity_date' => $activityDate,
            'start_time' => $startTime,
            'end_time' => $endTime,
            'participant_count' => $participantCount,
            'organizer' => $organizer,
            'status' => 'pending',
            'message' => '活动申请提交成功，请等待管理员审核'
        ], '活动申请提交成功');
        
    } catch (Exception $e) {
        $pdo->rollBack();
        error($e->getMessage());
    }
}

// 获取活动申请列表
function getActivityApplicationList() {
    global $pdo;
    
    $user = getCurrentUser();
    $page = max(1, intval($_GET['page'] ?? 1));
    $limit = min(50, max(1, intval($_GET['limit'] ?? 10)));
    $status = $_GET['status'] ?? '';
    $activityType = $_GET['activity_type'] ?? '';
    $offset = ($page - 1) * $limit;
    
    try {
        // 构建查询条件
        $whereClause = "WHERE user_id = ?";
        $params = [$user['id']];
        
        if ($status !== '') {
            $whereClause .= " AND status = ?";
            $params[] = intval($status);
        }
        
        if ($activityType !== '') {
            $whereClause .= " AND activity_type = ?";
            $params[] = $activityType;
        }
        
        // 查询活动申请列表
        $sql = "SELECT * FROM activity_applications 
                $whereClause 
                ORDER BY created_at DESC 
                LIMIT $limit OFFSET $offset";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $applications = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // 获取总数
        $countSql = "SELECT COUNT(*) as total FROM activity_applications $whereClause";
        $countStmt = $pdo->prepare($countSql);
        $countStmt->execute($params);
        $total = $countStmt->fetch(PDO::FETCH_ASSOC)['total'];
        
        // 处理数据格式
        $list = [];
        foreach ($applications as $application) {
            $canCancel = false;
            if ($application['status'] == 0 || $application['status'] == 1) {
                $activityDateTime = $application['activity_date'] . ' ' . $application['start_time'];
                $canCancel = strtotime($activityDateTime) > strtotime('+72 hours'); // 活动72小时前可取消
            }
            
            $statusMap = [0 => 'pending', 1 => 'approved', 2 => 'rejected', 3 => 'cancelled'];
            
            $list[] = [
                'id' => $application['id'],
                'activity_name' => $application['activity_name'],
                'activity_type' => $application['activity_type'],
                'activity_date' => $application['activity_date'],
                'start_time' => substr($application['start_time'], 0, 5),
                'end_time' => substr($application['end_time'], 0, 5),
                'participant_count' => intval($application['participant_count']),
                'organizer' => $application['organizer'],
                'contact_name' => $application['contact_name'],
                'contact_phone' => $application['contact_phone'],
                'status' => $statusMap[$application['status']] ?? 'unknown',
                'can_cancel' => $canCancel,
                'created_at' => $application['created_at'],
                'updated_at' => $application['updated_at']
            ];
        }
        
        success([
            'list' => $list,
            'pagination' => [
                'page' => $page,
                'limit' => $limit,
                'total' => intval($total),
                'pages' => ceil($total / $limit)
            ]
        ]);
        
    } catch (Exception $e) {
        error('获取活动申请列表失败: ' . $e->getMessage(), 500);
    }
}

// 获取活动申请详情
function getActivityApplicationDetail() {
    global $pdo;
    
    $user = getCurrentUser();
    $id = intval($_GET['id'] ?? 0);
    
    if (!$id) {
        error('申请ID不能为空');
    }
    
    try {
        $sql = "SELECT * FROM activity_applications WHERE id = ? AND user_id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$id, $user['id']]);
        $application = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$application) {
            error('活动申请不存在', 404);
        }
        
        $canCancel = false;
        if ($application['status'] == 0 || $application['status'] == 1) {
            $activityDateTime = $application['activity_date'] . ' ' . $application['start_time'];
            $canCancel = strtotime($activityDateTime) > strtotime('+72 hours');
        }
        
        $statusMap = [0 => 'pending', 1 => 'approved', 2 => 'rejected', 3 => 'cancelled'];
        
        success([
            'id' => $application['id'],
            'activity_name' => $application['activity_name'],
            'activity_type' => $application['activity_type'],
            'activity_date' => $application['activity_date'],
            'start_time' => substr($application['start_time'], 0, 5),
            'end_time' => substr($application['end_time'], 0, 5),
            'participant_count' => intval($application['participant_count']),
            'organizer' => $application['organizer'],
            'contact_name' => $application['contact_name'],
            'contact_phone' => $application['contact_phone'],
            'activity_description' => $application['activity_description'],
            'venue_requirements' => $application['venue_requirements'],
            'equipment_needs' => $application['equipment_needs'],
            'status' => $statusMap[$application['status']] ?? 'unknown',
            'can_cancel' => $canCancel,
            'review_note' => $application['review_note'],
            'created_at' => $application['created_at'],
            'updated_at' => $application['updated_at']
        ]);
        
    } catch (Exception $e) {
        error('获取活动申请详情失败: ' . $e->getMessage(), 500);
    }
}

// 取消活动申请
function cancelActivityApplication() {
    global $pdo;
    
    $user = getCurrentUser();
    $id = intval($_GET['id'] ?? 0);
    
    if (!$id) {
        error('申请ID不能为空');
    }
    
    try {
        $pdo->beginTransaction();
        
        // 获取申请信息
        $sql = "SELECT * FROM activity_applications WHERE id = ? AND user_id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$id, $user['id']]);
        $application = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$application) {
            throw new Exception('活动申请不存在');
        }
        
        if ($application['status'] == 3) {
            throw new Exception('申请已取消');
        }
        
        if ($application['status'] == 2) {
            throw new Exception('申请已被拒绝，无法取消');
        }
        
        // 检查是否可以取消（72小时前）
        $activityDateTime = $application['activity_date'] . ' ' . $application['start_time'];
        if (strtotime($activityDateTime) <= strtotime('+72 hours')) {
            throw new Exception('距离活动时间不足72小时，无法取消');
        }
        
        // 更新状态为取消
        $updateSql = "UPDATE activity_applications 
                     SET status = 3, updated_at = NOW() 
                     WHERE id = ?";
        $updateStmt = $pdo->prepare($updateSql);
        $updateStmt->execute([$id]);
        
        $pdo->commit();
        
        success(null, '活动申请已成功取消');
        
    } catch (Exception $e) {
        $pdo->rollBack();
        error($e->getMessage());
    }
}

// 获取活动申请统计
function getActivityApplicationStats() {
    global $pdo;
    
    $user = getCurrentUser();
    
    try {
        $sql = "SELECT 
                    COUNT(*) as total_applications,
                    SUM(CASE WHEN status = 0 THEN 1 ELSE 0 END) as pending_count,
                    SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) as approved_count,
                    SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END) as rejected_count,
                    SUM(CASE WHEN status = 3 THEN 1 ELSE 0 END) as cancelled_count,
                    SUM(participant_count) as total_participants
                FROM activity_applications 
                WHERE user_id = ?";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$user['id']]);
        $stats = $stmt->fetch(PDO::FETCH_ASSOC);
        
        // 获取活动类型分布
        $typeSql = "SELECT activity_type, COUNT(*) as count 
                   FROM activity_applications 
                   WHERE user_id = ? 
                   GROUP BY activity_type";
        $typeStmt = $pdo->prepare($typeSql);
        $typeStmt->execute([$user['id']]);
        $types = $typeStmt->fetchAll(PDO::FETCH_ASSOC);
        
        success([
            'total_applications' => intval($stats['total_applications']),
            'pending_count' => intval($stats['pending_count']),
            'approved_count' => intval($stats['approved_count']),
            'rejected_count' => intval($stats['rejected_count']),
            'cancelled_count' => intval($stats['cancelled_count']),
            'total_participants' => intval($stats['total_participants']),
            'activity_types' => $types
        ]);
        
    } catch (Exception $e) {
        error('获取统计信息失败: ' . $e->getMessage(), 500);
    }
}

// 获取活动类型列表
function getActivityTypes() {
    global $pdo;
    
    try {
        // 从数据库中获取已有的活动类型
        $sql = "SELECT DISTINCT activity_type, COUNT(*) as count 
                FROM activity_applications 
                WHERE activity_type IS NOT NULL AND activity_type != ''
                GROUP BY activity_type 
                ORDER BY count DESC, activity_type";
        
        $stmt = $pdo->query($sql);
        $types = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // 预定义的常见活动类型
        $defaultTypes = [
            ['activity_type' => '学术讲座', 'count' => 0],
            ['activity_type' => '文化展览', 'count' => 0],
            ['activity_type' => '教育培训', 'count' => 0],
            ['activity_type' => '社团活动', 'count' => 0],
            ['activity_type' => '学术研讨', 'count' => 0],
            ['activity_type' => '文艺演出', 'count' => 0],
            ['activity_type' => '主题沙龙', 'count' => 0],
            ['activity_type' => '公益活动', 'count' => 0]
        ];
        
        // 合并数据库中的类型和默认类型
        $existingTypes = array_column($types, 'activity_type');
        foreach ($defaultTypes as $defaultType) {
            if (!in_array($defaultType['activity_type'], $existingTypes)) {
                $types[] = $defaultType;
            }
        }
        
        success([
            'activity_types' => $types
        ]);
        
    } catch (Exception $e) {
        error('获取活动类型失败: ' . $e->getMessage(), 500);
    }
}

// 处理请求
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

try {
    switch ($method) {
        case 'GET':
            switch ($action) {
                case 'list':
                    getActivityApplicationList();
                    break;
                case 'detail':
                    getActivityApplicationDetail();
                    break;
                case 'stats':
                    getActivityApplicationStats();
                    break;
                case 'types':
                    getActivityTypes();
                    break;
                default:
                    error('无效的操作');
            }
            break;
            
        case 'POST':
            switch ($action) {
                case 'create':
                    createActivityApplication();
                    break;
                default:
                    error('无效的操作');
            }
            break;
            
        case 'PUT':
            switch ($action) {
                case 'cancel':
                    cancelActivityApplication();
                    break;
                default:
                    error('无效的操作');
            }
            break;
            
        default:
            error('不支持的请求方法');
    }
    
} catch (PDOException $e) {
    error('数据库错误: ' . $e->getMessage(), 500);
} catch (Exception $e) {
    error('服务器错误: ' . $e->getMessage(), 500);
}
?>